package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.model.dto.SaveTeachPlanDto;
import com.xuecheng.content.model.dto.TeachPlanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author jiangzhongxun
 */
@Slf4j
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Resource
    TeachplanMapper teachplanMapper;

    /**
     * 查询课程计划树形结构信息
     *
     * @param courseId 课程id
     * @return {@link List}<{@link TeachPlanDto}>
     */
    @Override
    public List<TeachPlanDto> findTeachPlanTree(Long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    /**
     * 新增/保存/修改课程计划
     *
     * @param saveTeachPlanDto 保存、修改课程计划 DTO
     */
    @Override
    public void saveTeachPlan(SaveTeachPlanDto saveTeachPlanDto) {
        /* 通过课程计划ID判断是新增还是修改 */
        Long teachPlanId = saveTeachPlanDto.getId();
        if (teachPlanId == null) {
            /* 新增 */
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachPlanDto, teachplan);
            /* 确定排序字段 */
            Long courseId = saveTeachPlanDto.getCourseId();
            Long parentId = saveTeachPlanDto.getParentid();
            int count = getTeachPlanCount(courseId, parentId);
            teachplan.setOrderby(count + 1);
            teachplanMapper.insert(teachplan);
        } else {
            /* 修改 */
            Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
            BeanUtils.copyProperties(saveTeachPlanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        }
    }

    /**
     * 获取课程计划统计
     *
     * @param courseId 课程id
     * @param parentId 父id
     * @return int
     */
    private int getTeachPlanCount(Long courseId, Long parentId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentId);
        return teachplanMapper.selectCount(queryWrapper);
    }

}
